﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web.UI;
using CacheProvider;
using CacheProvider.AppFabric;
using Microsoft.Practices.Composite.Presentation.Events;
using CacheProviderEntities;

public partial class CacheProviderTest : Page
{
    protected void Page_Load(object sender, EventArgs eventArgs)
    {
        if (!IsPostBack)
            CacheBroker.CacheProviderErrorEvent += new EventHandler<CacheProviderErrorEventArgs>(CacheBroker_CacheProviderErrorEvent);
    }

    void CacheBroker_CacheProviderErrorEvent(object sender, CacheProviderErrorEventArgs e)
    {

    }

    protected void ButtonAppFabricCacheSimpleTest_Click(object sender, EventArgs e)
    {
        string key = "SimpleCache";
        var data = CacheBroker.Get(key) as DataSet;
        if (data == null)
        {
            data = GetDataFromDB();
            CacheBroker.Put(key, data);
            Label1.Text = "SimpleCache: Read From Database";
        }
        else
        {
            Label1.Text = "SimpleCache: Read From Cache";
        }

        GridView1.DataSource = data;
        GridView1.DataBind();
    }


    protected void ButtonAppFabricCacheWithSQLDependency_Click(object sender, EventArgs e)
    {
        const string key = "SqlDependencyCache";
        var data = CacheBroker.Get<DataSet>(key);// as DataSet;
        if (data == null)
        {
            data = GetDataFromDB();
            var dependencyInfo = new DependencyInfo(CacheDependencyTypes.SQLDependency)
            {
                DBName = "AdventureWorks",
                DBConnectionString = GetConnectionString(),
                //SelectQuery = GetSQL(),
                IsSQLSelectQueryBased = true
            };

            dependencyInfo.SelectQueries.Add(GetSQL());

            CacheBroker.Put(key, data, string.Empty, TimeSpan.Zero, null, dependencyInfo, HydrateCache, key, ThreadOption.PublisherThread, true);

            Label1.Text = "SQLDependency: Read From Database";
        }
        else
        {
            Label1.Text = "SQLDependency: Read From Cache";
        }

        GridView1.DataSource = data;
        GridView1.DataBind();
    }

    private static void HydrateCache(object state)
    {
        var key = state as string;

        Debug.Assert(!string.IsNullOrEmpty(key));

        var data = GetDataFromDB();
        var dependencyInfo = new DependencyInfo(CacheDependencyTypes.SQLDependency)
        {
            DBName = "AdventureWorks",
            DBConnectionString = GetConnectionString(),
            //SelectQuery = GetSQL(),
            IsSQLSelectQueryBased = true
        };

        dependencyInfo.SelectQueries.Add(GetSQL());

        CacheBroker.Put<object>(key, data, string.Empty, TimeSpan.Zero, null, dependencyInfo, HydrateCache, key, ThreadOption.PublisherThread, true);
    }

    private static DataSet GetDataFromDB()
    {
        DataSet dataset;

        var sqlText = GetSQL();

        using (var connection =
           new SqlConnection(GetConnectionString()))
        {
            using (var command =
                new SqlCommand(sqlText, connection))
            {
                connection.Open();
                dataset = new DataSet();
                new SqlDataAdapter(command).Fill(dataset);
            }
        }
        return dataset;
    }

    private static string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrieve it from a configuration file.
        if (Environment.MachineName.Equals("IN8202039D"))
            return @"Data Source=SRVBLRCAF01\MSBLRTCTD01;Integrated Security=true;" +
              "Initial Catalog=AdventureWorks;";

        return @"Data Source=RAHUL-PC\SQL2008EXPRESS;Integrated Security=true;" +
          "Initial Catalog=AdventureWorks;";
    }

    private static string GetSQL()
    {
        return "SELECT Production.Product.ProductID, " +
        "Production.Product.Name, " +
        "Production.Location.Name AS Location, " +
        "Production.ProductInventory.Quantity " +
        "FROM Production.Product INNER JOIN " +
        "Production.ProductInventory " +
        "ON Production.Product.ProductID = " +
        "Production.ProductInventory.ProductID " +
        "INNER JOIN Production.Location " +
        "ON Production.ProductInventory.LocationID = " +
        "Production.Location.LocationID " +
        "WHERE ( Production.ProductInventory.Quantity <= 100 ) " +
        "ORDER BY Production.ProductInventory.Quantity, " +
        "Production.Product.Name;";
    }

}
